/*
 * @Descripttion: 
 * @Author: cuidm
 * @Date: 2022-07-01 09:39:35
 * @LastEditors: cuidm
 * @LastEditTime: 2022-08-12 12:38:26
 */
import React, { useEffect, useState } from "react";
import { Card, Affix, Button, Alert, Radio, Select, Input, Space, Row, Col, Table, message } from "antd";
import request, {requestIAM} from '@/utils/request';
import cmdbres from "@/data/cmdbres";
import hcpUtils from "@/utils/hcpUtils";
import "./index.less";
const user = hcpUtils.getUser();
const {filterArray} = hcpUtils;

const CategoryItem = ({ history, match, categoryId, info, filterArray, onFinish, ...pro }) => {

    const [categoryInfo, setCategoryInfo] = useState({});
    const [categoryName, setCategoryName] = useState('');//记录分类名称
    const [showAddCategory, setShowAddCategory] = useState(false);//显示添加分类

    const defaultItem = (item) => (
        <Card 
            title={<div>
                <span className="title"> {item.name} <span className="tip">内置</span></span><br/>
                <span className="child-id">#{item.id}</span>
            </div>}
            style={{ width: 300 }}
            hoverable
            {...pro}
        >
            {item?.children?.map((child, index)=> (
                <div className="child-item" key={index}>
                <div className="child-title">
                    <span className="content">{child.name}</span>
                    <span className="child-id">#{child.id}</span>
                </div>
                </div>
            ))}
        </Card>
    );

    const optItem =  (item) => (
        <Card 
            title={
                item.edit ? 
                <div style={{marginRight: 10, height: 44}}>
                    <Input 
                        value={categoryName} 
                        onChange={(e)=> {setCategoryName(e.target.value)}}
                        autoFocus
                    />
                </div>
                :
                <div onClick={()=> { setEdit(-1, false);} }>
                    <span className="title"> {item.name} </span><br/>
                    <span className="child-id">#{item.id}</span>
                </div>
            }
            style={{ width: 300 }}
            extra={
                item.edit ?
                <Space className="btns">
                    <span 
                        onClick={(e)=> {
                            cancelEdit(-1);
                            updateCategory(item, true);
                        }}
                    >确定</span>
                    <span onClick={(e)=> { cancelEdit(-1);}}>取消</span>
                </Space>
                :
                <Space className="btns">
                    <span 
                        className="iconfont icon-plus" 
                        onClick={()=> {
                            setEdit(-2, true);
                        }}
                    />
                    <span 
                        className="iconfont icon-delete" 
                        onClick={()=> {deleteCategory(item)}}
                    ></span>
                </Space> 
            }
            hoverable
            {...pro}
        >
            {item?.children?.map((child, index)=> (
                child.edit ?
                <div className="child-item" key={index}>
                <div className="child-title">
                    <Input 
                        style={{marginRight: 10}}
                        value={categoryName} 
                        onChange={(e)=> {setCategoryName(e.target.value)}}
                        autoFocus
                    />
                </div>
                <Space className="btns">
                        <span 
                            onClick={()=> {
                                cancelEdit(index);
                                updateCategory(child);
                            }}
                        >确定</span>
                        <span onClick={()=> { cancelEdit(index) }}>取消</span>
                    </Space>
                </div>:
                <div className="child-item" key={index}>
                <div className="child-title">
                    <span className="content">{child.name}</span>
                    <span className="child-id edit-id">#{child.id}</span>
                </div>
                <Space className="opt-btns">
                    <span 
                        className="iconfont icon-edit" 
                        onClick={()=> { 
                            setEdit(index, false);
                        }}
                    />
                    <span 
                        className="iconfont icon-delete" 
                        onClick={()=>{deleteCategory(child)}}
                    />
                </Space> 
                </div>
            ))}
            {
                showAddCategory ?
                <div className="child-item">
                <div className="child-title">
                    <Input 
                        style={{marginRight: 10}}
                        value={categoryName} 
                        onChange={(e)=> {setCategoryName(e.target.value)}}
                        autoFocus
                    />
                    <Space className="btns">
                        <span 
                            onClick={()=> {
                                addCategory(item);
                            }}
                        >确定</span>
                        <span 
                            onClick={()=> {
                                setShowAddCategory(false);
                                setCategoryName('');
                            }}
                        >取消</span>
                    </Space>
                </div>
                </div>
                :
                <div className="child-item">
                    <div className="child-title">
                        <span 
                            className="child-id" 
                            onClick={()=> {
                                setEdit(-2, true);
                            }}
                        >+ 添加</span>
                    </div>
                </div>
            }
            
        </Card>
    );

    const setEdit = (childIndex, isAddCategory) => {
        const arr = JSON.parse(JSON.stringify(categoryInfo));
        setCategoryName('');
        arr.edit = childIndex == -1 ? true: false; //-1代表修改是一级分类
        if(childIndex == -1) {
            arr.edit = true;
            setCategoryName(arr.name);
        } else {
            arr.edit = false;
        }
        
        if(arr.children) {
            arr.children.map((child, index) => {
                if(index == childIndex) {
                    child.edit = true;
                    setCategoryName(child.name);
                } else {
                    child.edit = false;
                }
            })
        }
        setCategoryInfo(arr);
        setShowAddCategory(isAddCategory);
    }

    const cancelEdit = (childIndex) => {
        const arr = JSON.parse(JSON.stringify(categoryInfo));
        if(childIndex == -1) {
            arr.edit = false;
        } else {
            arr.children[childIndex].edit = false;
        }
        setCategoryInfo(arr);
        setCategoryName('');
    }
    
    const updateCategory = async (obj, flag) => {
        if(!categoryName) {
            message.error("请输入分类名称");
            return;
        }
        try {
            const res = await request({
                ...cmdbres.updateServiceCategory(obj.id),
                data: {
                    bizId: obj.bizId,
                    name: categoryName,
                    rootId: obj.rootId,
                    parentId: obj.parentId,
                    author: user.staffName
                },
            });
            if (res && res.code == 200) {
                message.success("修改分类成功！");
                if(onFinish) onFinish();
            }
        } catch (error) {
            console.log(error);
        }
    }

    const deleteCategory = async (obj) => {
        setShowAddCategory(false);
        try {
            const res = await request({
                ...cmdbres.deleteServiceCategory(obj.id),
                params: {
                    author: user.staffName
                },
            });
            if (res && res.code == 200) {
                message.success("删除分类成功！");
                if(onFinish) onFinish();
            }
        } catch (error) {
            console.log(error);
        }    
    }

    const addCategory = async (obj) => {
        if(!categoryName) {
            message.error("请输入分类名称");
            return;
        }
        try {
            const res = await request({
                ...cmdbres.createServiceCategory,
                data: {
                    bizId: obj.bizId,
                    name: categoryName,
                    rootId: obj.rootId,
                    parentId: obj.id,
                    author: user.staffName
                },
            });
            if (res && res.code == 200) {
                message.success("添加分类成功！");
                setShowAddCategory(false);
                setCategoryName('');
                if(onFinish) onFinish();
            }
        } catch (error) {
            console.log(error);
        }
    }
    
    useEffect(() => {
       if(info) setCategoryInfo(info);
    }, [info])
    return (
        <>
            <div className="category-box">
                {
                    categoryInfo.buildIn ?  defaultItem(categoryInfo) : optItem(categoryInfo)
                }
            </div>
        </>
    );
};

export default CategoryItem;